"""etc3dump

Usage:
  etc3dump.py dump [--prefix=<pref>] [--file=<fn>]
  etc3dump.py restore [--file=<fn>]
  etc3dump.py (-h | --help)
  etc3dump.py --version

Options:
  -h --help         Show this screen.
  --version         Show version.
  --file=<fn>       Input/Output filename.
  --prefix=<pref>   Prefix to dump from.

"""


import etcd3
import json
from docopt import docopt


etcd = etcd3.client()


def dump_prefix(prefix, to_file):
    dump = {}
    for value, meta in etcd.get_prefix(prefix):
        dump[meta.key.decode('utf8')] = value.decode('utf8')
    with open(to_file, 'wt') as f:
        f.write(json.dumps(dump))


def load_prefix(from_file):
    with open(from_file, 'rt') as f:
        dump = json.loads(f.read())
        for k, v in dump.items():
            etcd.put(k, v)


def main(args):
    if args['dump']:
        dump_prefix(args['--prefix'], args['--file'])
    elif args['restore']:
        load_prefix(args['--file'])


if __name__ == '__main__':
    args = docopt(__doc__, version='etcd3dump')
    main(args)

